/*
 * Created on Aug 2, 2004
 */
package org.vectrics.company.web.struts;

import javax.servlet.jsp.JspException;

import org.apache.log4j.Logger;
import org.vectrics.SystemException;
import org.vectrics.company.Company;
import org.vectrics.company.CompanyPerson;
import org.vectrics.provider.CoreServiceLocator;
import org.vectrics.struts.VectricsActionData;
import org.vectrics.struts.VectricsStrutsAction;
import org.vectrics.user.Person;
import org.vectrics.user.web.struts.UserPrivilegesHelper;


/**
 * @author mmoore
 */
public class SaveCompanyPersonPrivilegeAction extends VectricsStrutsAction {
	private transient final Logger log = Logger.getLogger(this.getClass());
	
	protected String doExecute(VectricsActionData actionData) throws JspException {
		log.debug("doExecute() called");
		String forward = "success";
		
		CompanyPersonPrivilegeForm privForm = (CompanyPersonPrivilegeForm)actionData.getForm();
		Long personId = new Long(privForm.getPersonId());
		Person person = CoreServiceLocator.getPersonService().findPersonById(personId);

		Long companyId = new Long(privForm.getCompanyId());
		Company company = CoreServiceLocator.getCompanyService().findCompany(companyId);
		
		UserPrivilegesHelper userPrivilegeHelper = new UserPrivilegesHelper();
		if (company == null) {
			throw new SystemException("Company not found: " + privForm.getCompanyId());
		} else {
			boolean global = true;
			userPrivilegeHelper.saveRoles(actionData, person, company.getDomain(), global);
			
			global = false;
			userPrivilegeHelper.saveRoles(actionData, person, company.getDomain(), global);
		}

		
		CompanyPerson companyPerson = CoreServiceLocator.getCompanyService().findCompanyPerson(company, person);
		actionData.getRequest().setAttribute("companyPersonId", companyPerson.getId().toString());
		
		return(forward);
	}
	
	
}
